package com.thinkit.bigdata.core.util.ip;

import com.thinkit.bigdata.core.util.StringUtil;
import org.apache.log4j.Logger;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by BanAiQin on 2017/10/25.
 * 判断IP地址相关的方法
 */
public class IPUtil {

    private static Logger logger = Logger.getLogger(IPUtil.class);

    private static List<String> localIps = new ArrayList<>();

    static {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            //loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && !ip.isLoopbackAddress()
                            && ip.getHostAddress().indexOf(":") == -1) {

                        logger.info("本机的IP = " + ip.getHostAddress());
                        localIps.add(ip.getHostAddress());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean isLocalIP(String ip) {
        if (StringUtil.isEmpty(ip))
            return false;
        if (localIps.contains(ip))
            return true;
        return ip.equals("127.0.0.1") || ip.equals("localhost");
    }

    public static String getLocalIP() {
        for (String ip : localIps) {
            if (!ip.equals("127.0.0.1") || !ip.equals("localhost")) {
                return ip;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(isLocalIP("192.168.7.11"));
    }


}
